<template>
  <view class="group_settings_container">
    <custom-nav-bar title="群聊设置" />
    <view class="group_settings_content">
      <view class="setting_row info_row">
        <view class="group_avatar" @click="updateGroupAvatar">
          <my-avatar
            :src="storeCurrentConversation.faceURL"
            :isGroup="true"
            size="46"
          />
          <image
            v-if="isOwner"
            class="edit_icon"
            src="@/static/images/group_setting_edit.png"
            alt=""
          />
        </view>
        <view class="group_info">
          <view class="group_info_name">
            <text class="group_name"
              >{{ storeCurrentConversation.showName }}({{
                storeCurrentGroup.memberCount
              }})</text
            >
            <image
              v-if="isOwner || isAdmin"
              @click="toUpdateGroupName"
              style="width: 24rpx; height: 24rpx"
              src="@/static/images/group_edit.png"
              alt=""
            />
          </view>

          <text @click="copyGroupID" class="sub_title">{{
            storeCurrentConversation.groupID
          }}</text>
        </view>
        <image
          @click="toGroupQr"
          style="margin-right: 6rpx; width: 18px; height: 18px"
          src="@/static/images/group_setting_qrcode.png"
          alt=""
        />
      </view>

      <group-member-row
        :isNomal="!isAdmin && !isOwner"
        :groupID="storeCurrentConversation.groupID"
        :memberCount="storeCurrentGroup.memberCount"
        :groupMemberList="groupMemberList"
      />

      <view class="setting_row">
        <setting-item
          danger
          @click="() => (confirmType = isOwner ? 'Dismiss' : 'Quit')"
          :title="isOwner ? '解散群聊' : '退出群聊'"
          :border="false"
        />
      </view>

      <u-modal
        :content="getConfirmContent"
        asyncClose
        :show="confirmType !== null"
        showCancelButton
        @confirm="confirm"
        @cancel="() => (confirmType = null)"
      ></u-modal>
    </view>

    <u-toast ref="uToast"></u-toast>
  </view>
</template>

<script>
import { mapGetters } from "vuex";
import IMSDK, {
  GroupMemberRole,
  IMMethods,
} from "openim-uniapp-polyfill";
import CustomNavBar from "@/components/CustomNavBar/index.vue";
import MyAvatar from "@/components/MyAvatar/index.vue";
import SettingItem from "@/components/SettingItem/index.vue";
import GroupMemberRow from "./components/GroupMemberRow.vue";
import { getPurePath, uploadForm } from "@/util/common";

const ConfirmTypes = {
  Clear: "Clear",
  Dismiss: "Dismiss",
  Quit: "Quit",
};

export default {
  components: {
    CustomNavBar,
    MyAvatar,
    SettingItem,
    GroupMemberRow,
  },
  props: {},
  data() {
    return {
      confirmType: null,
      switchLoading: {
        pin: false,
        opt: false,
        mute: false,
      },
      groupMemberList: [],
    };
  },
  onShow() {
    this.getGroupMemberList();
  },
  watch: {
    "storeCurrentGroup.memberCount"() {
      this.getGroupMemberList();
    },
  },
  computed: {
    ...mapGetters([
      "storeCurrentConversation",
      "storeCurrentMemberInGroup",
      "storeCurrentGroup",
    ]),
    getConfirmContent() {
      if (this.confirmType === ConfirmTypes.Quit) {
        return "确定要退出当前群聊吗？";
      }
      if (this.confirmType === ConfirmTypes.Dismiss) {
        return "确定要解散当前群聊吗？";
      }
      return "";
    },
    isOwner() {
      return this.storeCurrentMemberInGroup.roleLevel === GroupMemberRole.Owner;
    },
    isAdmin() {
      return this.storeCurrentMemberInGroup.roleLevel === GroupMemberRole.Admin;
    },
    getGroupTypeStr() {
      return "工作群";
    },
  },
  methods: {
    getGroupMemberList() {
      IMSDK.asyncApi(IMSDK.IMMethods.GetGroupMemberList, IMSDK.uuid(), {
        groupID: this.storeCurrentConversation.groupID,
        filter: 0,
        offset: 0,
        count: !this.isAdmin && !this.isOwner ? 9 : 8,
      })
        .then(({ data }) => {
          console.log(data);
          this.groupMemberList = [...data];
        })
        .catch((err) => {
          console.log(err);
        });
    },
    toUpdateGroupName() {
      if (!this.isAdmin && !this.isOwner) {
        return;
      }

      uni.navigateTo({
        url: `/pages/conversation/updateGroupOrNickname/index?sourceInfo=${JSON.stringify(
          this.storeCurrentGroup,
        )}`,
      });
    },
    toGroupQr() {
      uni.navigateTo({
        url: `/pages/common/userOrGroupQrCode/index?sourceInfo=${JSON.stringify(
          this.storeCurrentGroup,
        )}`,
      });
    },
    copyGroupID() {
      uni.setClipboardData({
        data: this.storeCurrentGroup.groupID,
        success: () => {
          uni.hideToast();
          this.$nextTick(() => {
            uni.$u.toast("复制成功");
          });
        },
      });
    },
    updateGroupAvatar() {
      if (!this.isAdmin && !this.isOwner) {
        return;
      }

      uni.chooseImage({
        count: 1,
        sizeType: ["compressed"],
        success: async ({ tempFilePaths, tempFiles }) => {
          const path = tempFilePaths[0];
          const nameIdx = path.lastIndexOf("/") + 1;
          const typeIdx = path.lastIndexOf(".") + 1;
          let fileName = path.slice(nameIdx);
          let fileType = path.slice(typeIdx);

          if (uni.getSystemInfoSync().uniPlatform !== 'app') {
            fileType = tempFiles[0].type
            fileName = tempFiles[0].name
          }

          try {
            // #ifdef MP-WEIXIN
            const url = await uploadForm(tempFiles[0])
            // #endif
            // #ifdef APP-PLUS || H5
            const {
              data: { url },
            } = await IMSDK.asyncApi(IMMethods.UploadFile, IMSDK.uuid(), {
              filepath: getPurePath(tempFilePaths[0]),
              name: fileName,
              contentType: fileType,
              uuid: IMSDK.uuid(),
              file: tempFiles[0]
            });
            // #endif
            await IMSDK.asyncApi(IMSDK.IMMethods.SetGroupInfo, IMSDK.uuid(), {
              groupID: this.storeCurrentConversation.groupID,
              faceURL: url,
            });
            uni.$u.toast("修改成功");
          } catch (error) {
            uni.$u.toast("修改失败");
          }
        },
      });
    },
    confirm() {
      let funcName = "";
      let sourceID = this.storeCurrentConversation.groupID;
      if (this.confirmType === ConfirmTypes.Quit) {
        funcName = IMSDK.IMMethods.QuitGroup;
      }
      if (this.confirmType === ConfirmTypes.Dismiss) {
        funcName = IMSDK.IMMethods.DismissGroup;
      }
      IMSDK.asyncApi(funcName, IMSDK.uuid(), sourceID)
        .then(() => {
          uni.$u.toast("操作成功");
          if (this.confirmType === ConfirmTypes.Clear) {
            this.$store.commit("message/SET_HISTORY_MESSAGE_LIST", []);
            this.$store.commit("message/SET_PREVIEW_IMAGE_LIST", []);
          } else {
            setTimeout(
              () =>
                uni.switchTab({
                  url: "/pages/conversation/conversationList/index",
                }),
              250,
            );
          }
        })
        .catch(() => uni.$u.toast("操作失败"))
        .finally(() => (this.confirmType = null));
    },
  },
};
</script>

<style lang="scss" scoped>
.group_settings_container {
  @include colBox(false);
  height: 100vh;
  background-color: #f6f6f6;

  .group_settings_content {
    overflow-y: auto;
  }

  .setting_row {
    background-color: #fff;
    margin: 24rpx;
    border-radius: 6px;
    overflow: hidden;
  }

  .info_row {
    @include vCenterBox();
    padding: 36rpx 44rpx;

    .group_avatar {
      margin-right: 16rpx;
      position: relative;

      .edit_icon {
        position: absolute;
        right: -6rpx;
        bottom: -6rpx;
        width: 11px;
        height: 11px;
      }
    }

    .group_info {
      min-height: 46px;
      display: flex;
      flex: 1;
      flex-direction: column;
      align-items: flex-start;
      justify-content: space-between;

      &_name {
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;

        .group_name {
          // @include nomalEllipsis();
          font-size: 34rpx;
          max-width: 380rpx;
          margin-right: 24rpx;
        }
      }

      .sub_title {
        @include nomalEllipsis();
        margin-bottom: 0;
        font-size: 28rpx;
        color: #999;
      }
    }
  }
}
</style>
